﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using Me.Amon.Da.Db;
using Me.Amon.Da.Db.POS;
using Me.Amon.POS.C;
using Me.Amon.Util;

namespace Me.Amon.POS
{
    public partial class UpdateTerminal : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }

            var user = WebUtil.CurrentUser(Session);
            if (user.Rank < IUser.LEVEL_01)
            {
                Response.Redirect(IEnv.HOME_PAGE);
                return;
            }

            var corp = Request["corp"];
            if (!CharUtil.IsValidateCode(corp))
            {
                corp = "0";
            }
            var shop = Request["shop"];
            if (!CharUtil.IsValidateCode(shop))
            {
                shop = "0";
            }
            var pos = Request["pos"];

            TbTerminalAddr.MaxLength = CTerminal.ADDR;
            TbTerminalName.MaxLength = CTerminal.NAME;
            var dba = new RDBEngine();

            dba.AddTable(DShop.TABLE);
            dba.AddColumn(DShop.CODE);
            dba.AddColumn(DShop.NAME);
            dba.AddWhere(DShop.CORP_ID, corp);

            var dt = dba.ExecuteSelect();
            var cnt = dt.Rows.Count;

            string name;
            string code;
            if (cnt > 0)
            {
                for (int i = 0; i < cnt; i += 1)
                {
                    name = dt.Rows[i][DShop.NAME] as string;
                    code = dt.Rows[i][DShop.CODE] as string;
                    LbShop.Items.Add(new ListItem { Text = name, Value = code });
                    CbShop.Items.Add(new ListItem { Text = name, Value = code });
                }
                if (corp == "0")
                {
                    LbShop.Items.Add(new ListItem { Text = "未知", Value = "MD000000" });
                    CbShop.Items.Add(new ListItem { Text = "未知", Value = "MD000000" });
                }
                //LbShop.SelectedValue = dt.Rows[0][DShop.CODE] as string;
                //CbShop.SelectedValue = dt.Rows[0][DShop.CODE] as string;
            }
            else
            {
                LbShop.Items.Add(new ListItem { Text = "未知", Value = "MD000000" });
                CbShop.Items.Add(new ListItem { Text = "未知", Value = "MD000000" });
            }

            if (CharUtil.IsValidateHash(pos))
            {
                dba.Reset();
                ReadTerminal(dba, corp, shop, pos);
            }
        }

        #region 事件处理
        protected void BtUpdateTerminal_Click(object sender, EventArgs e)
        {
            SaveTerminal();
        }

        protected void BtCancelTerminal_Click(object sender, EventArgs e)
        {
            var corp = Request["corp"];
            if (!CharUtil.IsValidateCode(corp))
            {
                corp = "0";
            }
            Response.Redirect("~/POS/Terminals.aspx?corp=" + corp);
        }
        #endregion

        private void ReadTerminal(RDBEngine dba, string corp, string shop, string pos)
        {
            dba.AddTable(DTerminal.TABLE);
            dba.AddWhere(DTerminal.CORP_ID, corp);
            if (shop != "0")
            {
                dba.AddWhere(DTerminal.SHOP_ID, shop);
            }
            dba.AddWhere(DTerminal.ID, pos);
            var dt = dba.ExecuteSelect();
            if (dt.Rows.Count != 1)
            {
                return;
            }

            DataRow row = dt.Rows[0];
            HdId.Value = pos;
            TbTerminalCode.Text = "" + row[DTerminal.CODE];
            TbTerminalName.Text = "" + row[DTerminal.NAME];
            LbShop.SelectedValue = "" + row[DTerminal.SHOP_ID];
            CbShop.SelectedValue = "" + row[DTerminal.SHOP_ID];
            TbTerminalAddr.Text = "" + row[DTerminal.ADDR];
            CkTerminalStatus.Checked = (CTerminal.STATUS_DISABLED == (int)row[DTerminal.STATUS]);
        }

        private void SaveTerminal()
        {
            LlErr.Text = "";
            var id = HdId.Value;


            var terminalName = TbTerminalName.Text.Trim();
            if (!WebUtil.IsValid(terminalName, "终端名称", CTerminal.NAME, LlErr))
            {
                return;
            }

            #region 检测门店的重复性
            var dba = new RDBEngine();
            dba.AddTable(DTerminal.TABLE);
            dba.AddColumn(DTerminal.NAME, "terminal");
            dba.AddWhere(DTerminal.NAME, terminalName);
            dba.AddWhere(DTerminal.SHOP_ID, CbShop.SelectedValue);
            dba.AddWhere(DTerminal.STATUS, CTerminal.STATUE_ENABLED.ToString(), false);

            if (CharUtil.IsValidateHash(id))
            {
                dba.AddWhere(DTerminal.ID, "!=", id, true);
            }
            var dt = dba.ExecuteSelect();
            if (dt.Rows.Count != 0)
            {
                LlErr.Text = string.Format("在 \"{0}\" 门店中已存在名为 \"{1}\" 的终端！", CbShop.SelectedItem.Text, terminalName);
                return;
            }
            #endregion

            var corp = Request["corp"];
            if (!CharUtil.IsValidateCode(corp))
            {
                corp = "0";
            }

            //var user = WebUtil.CurrentUser(Session);
            bool isUpdate = CharUtil.IsValidateHash(id);
            string code = "";
            if (!isUpdate)
            {
                dba.Reset();
                code = KeyUtil.NextTerminalKey(dba, corp);
            }

            dba.Reset();
            dba.AddTable(DTerminal.TABLE);
            dba.AddParam(DTerminal.CORP_ID, corp);
            dba.AddParam(DTerminal.SHOP_ID, CbShop.SelectedValue);
            dba.AddParam(DTerminal.NAME, terminalName);
            dba.AddParam(DTerminal.ADDR, TbTerminalAddr.Text.Trim());
            dba.AddParam(DTerminal.STATUS, CkTerminalStatus.Checked ? CTerminal.STATUS_DISABLED : CTerminal.STATUE_ENABLED);
            dba.AddParam(DTerminal.UPDATE_TIME, DTerminal.NOW, false);
            if (isUpdate)
            {
                dba.AddWhere(DTerminal.ID, id);
                dba.ExecuteUpdate();

                Response.Redirect("~/POS/Terminals.aspx?corp=" + corp);
            }
            else
            {
                id = HashUtil.UtcTimeInHex();
                dba.AddParam(DTerminal.ID, id);
                dba.AddParam(DTerminal.CODE, code);
                dba.AddParam(DTerminal.CREATE_TIME, DEmp.NOW, false);
                dba.ExecuteInsert();

                ShowDef_Last(CbShop.SelectedValue);
            }
        }

        private void ShowDef_Last(string value)
        {
            HdId.Value = "";
            TbTerminalCode.Text = "";
            TbTerminalName.Text = "";
            TbTerminalAddr.Text = "";
            CbShop.SelectedValue = value;
            CkTerminalStatus.Checked = false;
        }

        private void ShowDef()
        {
            HdId.Value = "";
            TbTerminalCode.Text = "";
            TbTerminalName.Text = "";
            TbTerminalAddr.Text = "";
            CbShop.SelectedIndex = 0;
            CkTerminalStatus.Checked = false;
        }
    }
}